import { isString, toObject, searchCover, safeGet, isArray } from '@/common.js'
/**
 * 数据回填到模板中，并返回带有数据的模板
 * @param {*} formTemplateData 数据
 * @param {*} formTemplate 被序列化后的数据'{name:'zz', age:'18'}'
 * @param {*} disabled 是否禁用
 * @returns 
 */
export const data2Template = function (formTemplateData, formTemplate, disabled = false) {
  formTemplate = formTemplate && isString(formTemplate) ? JSON.parse(formTemplate) : (formTemplate || []) // 随访表单
  formTemplateData = formTemplateData && isString(formTemplateData) ? JSON.parse(formTemplateData) : (formTemplateData || {})
  // console.log(formTemplate)
  // console.log(formTemplateData)
  // 1、key <-----> value值进行回填
  const writeVal = v => Object.keys(v).reduce((prev, item) => {
    // 字段不包含value的话，正常赋值
    if(!item.includes('value')){ prev[item] = v[item]}
    // 字段为包含key，对key1字段赋值为value1  key2赋值为value2
    if(item.includes('key')) {
      let valueX = formTemplateData[v[item]]
      if(['uploadImg', 'uploadFile'].includes(v.type) && isString(valueX)) {
        // console.log(valueX)
        valueX = safeGet(() => JSON.parse(valueX), []) // valueX = valueX.replace(/=/g, ':')
      }
      prev[item.replace('key', 'value')] = valueX
    }
    prev._disabled = v.disabled // 对初始的是否禁用的状态做一个备份
    prev.disabled = disabled
    return prev
  }, {})
  formTemplate = formTemplate.map(v => v.type == 'split' ? {...v, children: v.children.map(k=> writeVal(k)) } : writeVal(v))
  // console.log(formTemplate)
  // 2、对单选、多选、症状中options选项进行是否选中的加工
  const writeSelect = v => {
    if(['select', 'radio', 'checkbox', 'symptom'].includes(v.type)) {
      if(v.options.length > 0 && (isString(v.value) || isString(v.value1))) {
        v.options = v.options.map(k => ({...k, isChecked: (((v.value || '') + (v.value1 || '')).split(',')).includes(k.id)}))
      }
    }
    return v
  }
  formTemplate = formTemplate.map(v =>  v.type == 'split' ? {...v, children: v.children.map(k=> writeSelect(k)) } : writeSelect(v))
  // 3、对单选下拉的控制的关联字段进行处理(前提是：第二步options选项中isChecked字段处理完毕)
  let linkArr = formTemplate.filter(v => ['select', 'radio'].includes(v.type)).map(v => v.options.filter(k => k.isChecked && k.link))
  linkArr = linkArr.flat(2)
  linkArr.forEach(linkItem => { formTemplate = searchCover(formTemplate, v => linkItem.link.split(',').includes(v.key), v => ({...v, _disabled: linkItem.type == 1})) })
  return formTemplate
}
/**
 * 模板转数据格式
 * @param {*} formTemplate 
 * @returns 
 * {name: '', age: ''}
 */
export const template2Data = function (formTemplate) {
  const getObj = v => Object.keys(v).reduce((prev, item) => {
    if(item.includes('key')) {
      const value = v[item.replace('key', 'value')]
      prev[v[item]] = isString(value) ? value : JSON.stringify(value)
    }
    return prev
  }, {})
  const formTemplateData = formTemplate.map(v => v.type == 'split' ? v.children.map(k=> getObj(k)) : getObj(v))
  const keyValObj = toObject(formTemplateData.flat(2))
  // console.log(keyValObj)
  return keyValObj
}
/**
 * 处理数据的必填
 * @param {*} formTemplate 
 * 返回加工之后的数据
 */
export const processRequired = function (formTemplate) {
  return formTemplate.map(v => {
    if(v.required) {
      if(['currentAndTarget', 'bloodPressure'].includes(v.type)) {
        v.errmsg = v.value1 && v.value2 ? '' : `请填写${v.label}`
      } else if(['uploadFile', 'uploadImg'].includes(v.type)){
        const fileArr = safeGet(() => JSON.parse(v.value), v.value) || []
        v.errmsg = isArray(fileArr) && fileArr.length ? '' : `请上传${v.label}`
      } else if(['input', 'textarea'].includes(v.type)) {
        v.errmsg = v.value ? '' : `请填写${v.label}`
      } else if(['radio', 'checkbox', 'select', 'date', 'symptom', 'pulseDorsalis'].includes(v.type)){
        v.errmsg = (v.value || v.value1) ?  '' : `请选择${v.label}`
      }
      // 处理足背动的右侧选项必填
      if(['pulseDorsalis'].includes(v.type)) {
        if(!v.value1) {
          v.errmsg = `请选择${v.label}`
        } else if(['2', '3'].includes(v.value1) && !v.value2) {
          v.errmsg = `请选择${({2:'减弱', 3: '消失'})[v.value1]}位置`
        }
      }
    } else if(['pulseDorsalis'].includes(v.type)){
      v.errmsg = ['2', '3'].includes(v.value1) && !v.value2 ? `请选择${({2:'减弱', 3: '消失'})[v.value1]}位置` : ''
    }
    return v
  })
}